//
//  AddAnnViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/3/25.
//

#import "AddAnnViewController.h"
#import "AddressBottomView.h"
#import "AddAnntionView.h"
#import "AddSuccessfulViewController.h"
@interface AddAnnViewController ()<MKMapViewDelegate,UITextFieldDelegate>
@property (nonatomic , strong) MKMapView * mapView;
@property (nonatomic , strong) UITextField * textField;
@property (nonatomic , strong) UILabel * addressLabel;
@property (nonatomic , strong) HeaderView * addButton;
@property (nonatomic , strong) CLPlacemark * seletedPlace;
@property (nonatomic , strong) SQCustomButton * dingwei;
@end

@implementation AddAnnViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[SQCLLocationManager sharedManager] SQ_startUpdatingLocation];
    // Do any additional setup after loading the view.
}

- (void)SQ_UIViewForSelfView{
    
    [self.view addSubview:self.mapView];
    [self SQ_setMap];
    SQCustomButton * add = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(30, 30) midmargin:0];
    add.image = SQGetImage(@"不喜欢");
    [self.view addSubview:add];
    [add mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(TopHeight-50);
        make.size.mas_equalTo(50);
        make.right.equalTo(self.view.mas_right).offset(-4);
    }];
    WS(weakSelf);
    [add setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    
    UIImageView * image = [[UIImageView alloc]init];
    image.image = SQGetImage(@"datouzhen");
    image.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self.view);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(40);
    }];
    [self.view addSubview:self.addressLabel];
    [self.addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(image.mas_top).offset(-4);
        make.width.mas_equalTo(SCREEN_WIDETH/2.f);
    }];
    
    [self.view addSubview:self.textField];
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(SCREEN_WIDETH-120);
        make.height.mas_equalTo(40);
        make.top.equalTo(self.view).offset(TopHeight-10);
    }];
    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(SQ_resignFirstResponder)];
   
    NSOperationQueue*  mainQueue = [NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQueue usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf.mapView addGestureRecognizer:tap];
    }];
    [nc addObserverForName:UIKeyboardWillHideNotification object:nil queue:mainQueue usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf.mapView removeGestureRecognizer:tap];
    }];
    
    [self.view addSubview:self.addButton];
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(SCREEN_WIDETH-60);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-30);
        make.height.mas_equalTo(48);
    }];
    
    [self.view addSubview:self.dingwei];
    [self.dingwei mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-100);
           make.size.mas_equalTo(50);
            make.right.equalTo(self.view.mas_right).offset(-10);
    }];
    [self.dingwei setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf SQ_setMap];
    }];
}
-(void)SQ_setMap{
    CLLocationCoordinate2D coordinate2D = CLLocationCoordinate2DMake([UserModel share].lat, [UserModel share].lng);
       // 设置地图显示区域的缩放级别
       float zoomLevel = 0.002;
       // 初始化一个常量，表示地图对象的显示区域
       MKCoordinateRegion region = MKCoordinateRegionMake(coordinate2D, MKCoordinateSpanMake(zoomLevel, zoomLevel));
       // 设置地图对象的显示区域
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}


//位置已经改变了
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    
    self.addButton.btn.enabled = YES;
    CLLocationCoordinate2D  location =  [self.mapView convertPoint:CGPointMake(SCREEN_WIDETH/2.f, SCREEN_HEIGHT/2.f) toCoordinateFromView:self.mapView];
         CLGeocoder *gecoder = [[CLGeocoder alloc]init];
         CLLocation *locations = [[CLLocation alloc]initWithLatitude:location.latitude longitude:location.longitude];
    WS(weakSelf);
        [gecoder reverseGeocodeLocation:locations completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            
            if (placemarks.count > 0) {
                CLPlacemark * place = placemarks.firstObject;
                self.seletedPlace = placemarks.firstObject;
                NSString *city = place.locality;
                if ([city isNotEmpty]) {
                    weakSelf.addressLabel.text = [NSString stringWithFormat:@"%@%@%@%@",place.country,place.locality,place.thoroughfare,place.name];
                   
                } else {
                    weakSelf.addressLabel.text = [NSString stringWithFormat:@"%@%@%@%@",place.country,place.administrativeArea,place.thoroughfare,place.name];
                }
                weakSelf.addressLabel.text = [weakSelf.addressLabel.text stringByReplacingOccurrencesOfString:@"null" withString:@""];
            }
        }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.textField resignFirstResponder];
    if ([textField.text isNotEmpty]) {
        CLGeocoder *gecoder = [[CLGeocoder alloc]init];
        WS(weakSelf);
        [gecoder geocodeAddressString:textField.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            DTLog(@"---%@",error);
            if (error!=nil) {
                [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"请输入较为详细地址!")];
                return ;
            }
            if (placemarks.count==0) {
                [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"搜索结果为空!")];
                return ;
             }
            [weakSelf SQ_showAddressView:placemarks];
        }];
    }
    return  YES;
}
-(void)SQ_resignFirstResponder{
    [self.textField resignFirstResponder];
}

-(void)SQ_showAddressView:(NSArray<CLPlacemark *> *)placemarks{
    AddressBottomView * vc = [[AddressBottomView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, 560)];
    [vc SQ_relodeView:placemarks];
    LSTPopView * pop = [LSTPopView initWithCustomView:vc parentView:self.view popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleBottom;
    pop.isStack = YES;
    [pop pop];
    LSTPopViewWK(pop)
    [pop setBgClickBlock:^{
        [wk_pop dismiss];
    }];
    WS(weakSelf);
    [vc setAddressBlock:^(CLPlacemark * _Nonnull model) {
        [wk_pop dismiss];
        [weakSelf SQ_mapForAddress:model];
    }];
}
-(void)SQ_mapForAddress:(CLPlacemark*)model{
    CLLocationCoordinate2D coordinate2D = CLLocationCoordinate2DMake(model.location.coordinate.latitude, model.location.coordinate.longitude);
       // 设置地图显示区域的缩放级别
       float zoomLevel = 0.001;
       // 初始化一个常量，表示地图对象的显示区域
       MKCoordinateRegion region = MKCoordinateRegionMake(coordinate2D, MKCoordinateSpanMake(zoomLevel, zoomLevel));
       // 设置地图对象的显示区域
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}

-(void)SQ_addAnntionForMap{
    if (self.seletedPlace == nil) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"定位异常")];
        [[SQCLLocationManager sharedManager] SQ_startUpdatingLocation];
        [self SQ_setMap];
        return;
    }
    AddAnntionView * vc = [[AddAnntionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, 550)];
    vc.addressLabel.text = self.addressLabel.text;
    vc.place = self.seletedPlace;
    LSTPopView * pop = [LSTPopView initWithCustomView:vc parentView:self.view popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleBottom;
    pop.isAvoidKeyboard = NO;
    [pop pop];
    LSTPopViewWK(pop)
    [pop setBgClickBlock:^{
        [wk_pop dismiss];
    }];
    WS(weakSelf);
    [vc setAddSuccessfulBlock:^{
        [wk_pop dismiss];
        AddSuccessfulViewController * vc = [[AddSuccessfulViewController alloc]init];
        [weakSelf SQ_presentFull:vc];
    }];
}


- (void)dealloc {
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode  = MKUserTrackingModeNone;
    [_mapView.layer removeAllAnimations];
    [_mapView removeAnnotations:_mapView.annotations];
    [_mapView removeOverlays:_mapView.overlays];
    [_mapView removeFromSuperview];
    _mapView.delegate = nil;
    _mapView = nil;
}
 
/** 懒加载地图视图 */
- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
        /** 设置地图类型 */
        _mapView.mapType = MKMapTypeMutedStandard;
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        //设置地图可缩放
        _mapView.zoomEnabled = YES;
        //设置地图可滚动
        _mapView.scrollEnabled = YES;
        //设置地图可旋转
        _mapView.rotateEnabled = YES;
        //设置显示用户显示位置
        _mapView.showsUserLocation = YES;
        //为MKMapView设置delegate
        _mapView.delegate = self;
        _mapView.showsBuildings = YES;
        _mapView.showsTraffic = YES;
    }
    return _mapView;
}
 
- (UILabel *)addressLabel{
    if (!_addressLabel) {
        _addressLabel = [[UILabel alloc]init];
//        _addressLabel.backgroundColor = SQHexColor(@"#000000", 0.3);
        _addressLabel.font = FONT_REGULAR(12);
        _addressLabel.textColor = UIColor.whiteColor;
        _addressLabel.numberOfLines = 0;
        _addressLabel.textAlignment = NSTextAlignmentCenter;
//        _addressLabel.layer.cornerRadius = 2;
    }
    return _addressLabel;
}

- (UITextField *)textField{
    if (!_textField) {
        _textField = [[UITextField alloc]init];
        _textField.backgroundColor = SQHexColor(@"#FFFFFF", 0.4);
        _textField.placeholder = SQNSLocalString(@"输入你想查找的地址关键词");
        _textField.textColor = UIColor.whiteColor;
        _textField.layer.cornerRadius = 20;
        _textField.layer.borderColor = UIColor.whiteColor.CGColor;
        _textField.layer.borderWidth = 1;
        _textField.font = FONT_REGULAR(14);
        _textField.delegate = self;
        _textField.returnKeyType = UIReturnKeyDone;
        _textField.layer.masksToBounds = YES;
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 36)];
        UIImageView * lefe = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 16, 16)];
        lefe.image = SQGetImage(@"输入");
        lefe.contentMode = UIViewContentModeScaleAspectFit;
        [bgView addSubview:lefe];
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.leftView = bgView;
//        [_textField setValue:SQColor999999 forKeyPath:@"placeholderLabel.textColor"];
    }
    return _textField;
}
- (HeaderView *)addButton{
    if (!_addButton) {
        _addButton = [[HeaderView alloc]init];
        _addButton.image = @"矩形";
        _addButton.colorString = @"#FFFFFF";
        [_addButton.btn addTarget:self action:@selector(SQ_addAnntionForMap) forControlEvents:UIControlEventTouchUpInside];
        _addButton.layer.cornerRadius = 6;
        _addButton.layer.masksToBounds = YES;
        _addButton.text = SQNSLocalString(@"添加该地点");
        _addButton.font = FONT_MEDIUM(18);
    }
    return _addButton;
}
- (SQCustomButton *)dingwei{
    if (!_dingwei) {
        _dingwei = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(30, 30) midmargin:0];
        _dingwei.image = SQGetImage(@"zishendingwei");
    }
    return _dingwei;
}
@end
